/public/opengrok$ cat setup-opengrok-projects.sh 
#!/bin/bash
#
# Copyright (C) 2023, guyongqiangx All Rights Reserved.
# 
# File Name: setup-opengrok-projects.sh 
#    Author: guyongqiangx
#      Blog: https://blog.csdn.net/guyongqiangx
#      Date: 2023-02-11
#      Info: 批量配置 opengrok 项目
#

# opengrok 安装目录
OPENGROK_APP_DIR=/opt/opengrok/dist/opengrok-1.7.42
# tomcat 安装目录
TOMCAT_APP_DIR=/opt/tomcat/apache-tomcat-10.0.27
# 代码项目根目录
PROJECT_ROOT_DIR=/public/opengrok
# 服务器访问地址
SERVER_URL=http://localhost:8080

# sudo 方式下用普通用户执行命令: "sudo -u username command"
USER="sudo -u guyongqiangx"

# 带一个参数，当前项目
setup_opengrok_project() {
    PROJECT=$1

    DATA_DIR=${PROJECT_ROOT_DIR}/data/${PROJECT}
    ETC_DIR=${PROJECT_ROOT_DIR}/etc/${PROJECT}
    SRC_DIR=${PROJECT_ROOT_DIR}/src/${PROJECT}
    LOG_DIR=${PROJECT_ROOT_DIR}/log/${PROJECT}

    # 1. 准备项目的 data, etc 和 log 目录
    ${USER} mkdir -p ${DATA_DIR} ${ETC_DIR} ${LOG_DIR}

    # 2. 准备项目的 logging.properties 文件
    ${USER} cp ${OPENGROK_APP_DIR}/doc/logging.properties ${ETC_DIR}

    # 3. 更新项目的 logging.properties 文件
    PATTERN="java.util.logging.FileHandler.pattern =.*"
    REPLACE="java.util.logging.FileHandler.pattern = ${LOG_DIR}/opengrok%g.%u.log"

    # TODAY=$(date +%F)
    # AUTHOR=guyongqiangx
    # COMMENTS="$TODAY $AUTHOR - Set logging file location to ${PROJECT} etc dir"
    # sed -i "s!^${PATTERN}!# &\n# ${COMMENTS}\n${REPLACE}!" ${ETC_DIR}/logging.properties
    ${USER} sed -i "s!^${PATTERN}!# &\n${REPLACE}!" ${ETC_DIR}/logging.properties

    # 4. 复制模板 source.war 到 tomcat 的 webapps 目录
    sudo cp ${OPENGROK_APP_DIR}/lib/source.war ${TOMCAT_APP_DIR}/webapps/${PROJECT}.war 

    # 5. 更新项目的 tomcat 配置文件 web.xml
    sudo opengrok-deploy -c ${ETC_DIR}/configuration.xml ${OPENGROK_APP_DIR}/lib/source.war ${TOMCAT_APP_DIR}/webapps/${PROJECT}.war

    # 6. 索引项目数据
    ${USER} java \
        -Djava.util.logging.config.file=${ETC_DIR}/logging.properties \
        -jar ${OPENGROK_APP_DIR}/lib/opengrok.jar \
        -c /usr/local/bin/ctags \
        -s ${SRC_DIR}  \
        -d ${DATA_DIR} \
        -P -S -G -W ${ETC_DIR}/configuration.xml \
        -U ${SERVER_URL}/${PROJECT} &> ${LOG_DIR}/index.log &
    ${USER} echo "index project ${PROJECT} in background..."
}

# for project in uboot-v2009.01  uboot-v2013.01  uboot-v2014.01  uboot-v2015.01
for project in $(ls ${PROJECT_ROOT_DIR}/src)
do
    echo "setup project ${project}..."
    setup_opengrok_project ${project}
done

while [ $(ps -ef | grep -c opengrok.jar) -ne 1 ]
do
    ${USER} echo -n .
    sleep 2
done

# sudo service tomcat restart
sudo systemctl restart tomcat.service
echo "done!"
